<template>
  <view class="lz-tree">
    <view class="example-body">
      <uni-search-bar class="uni-search-bar" clearButton="always" :placeholder="$t('关键词')" radius="100" @cancel="cancel"
                      @confirm="search" @input="input"/>
    </view>
    <ly-tree ref="tree" :checkStrictly="true" :currentNodeKey="currentNodeKeyData" :defaultCheckedKeys="defaultCheckedKeysData" :filter-node-method="filterNode" :props="defaultProps"
             :tree-data="treeData" checkOnClickNode highlightCurrent
             node-key="id" showRadio @radio-change="handleRadioChange">
    </ly-tree>
    <view v-if="selectValue" class="footer">
      <view class="left">{{$t('已选择')}}：{{ selectValue.name }}</view>
      <u-button :loading="loading" size="medium" type="primary" @click="endEmployees">{{$t('绑定')}}</u-button>
    </view>
  </view>
</template>

<script>
import uniSearchBar from '@/components/uni-search-bar/uni-search-bar.vue'
import {
  mapGetters,
  mapMutations
} from "vuex"

export default {
  components: {
    uniSearchBar
  },
  computed: {
    ...mapGetters(["userInfo", "api", "Bluetooth"])
  },
  data() {
    return {
      loading: false,
      treeData: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      },
      selectValue: '', //已选择
      defaultCheckedKeysData: [], //回显勾选
      currentNodeKeyData: '', //回显高亮
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  onBackPress(options) {
    uni.closeBluetoothAdapter();
    if (options.from === 'navigateBack') {
      return false;
    }
    uni.navigateBack({
      delta: 1
    });
    return true;
  },
  onLoad(e) {
    uni.setNavigationBarTitle({title: this.$t('设备绑定')})

    //停止搜索蓝牙
    this.$lizhao.bluetooth.stopBluetoothDevicesDiscovery()
  },
  onReady() {
    this.$lizhao.bluetooth.initParams()
    //获取组织列表
    this.getBindDepartments()
    //监听回复
    uni.$off('onBLECharacteristicValueChange')
    uni.$on('onBLECharacteristicValueChange', (res) => {
      //console.log(res);
      if (res.cmd === 7) {//设备绑定
        this.loading = false
        uni.showToast({
          title: this.$t('设备绑定成功')
        });
        uni.closeBluetoothAdapter();
        setTimeout(() => {
          uni.redirectTo({
            url: '../IntelligentSeal/IntelligentSeal?id=' + this.Bluetooth.device.sn + '&from=扫码'
          });
        }, 500)
      }
    })
  },
  methods: {
    //回显
    showData(e) {
      //console.log(e);
      if (e.departmentId) {
        this.defaultCheckedKeysData = [e.departmentId] //回显勾选
        this.currentNodeKeyData = e.departmentId //回显高亮
        this.selectValue = { //已选择
          name: e.departmentName,
          id: e.departmentId
        }
      }

    },
    //获取设备绑定的组织列表
    getBindDepartments() {
      this.$u.post(this.api.GLOBAL_auth_department_getBindDepartments, {
        sn: this.Bluetooth.device.sn
      }).then(res => {
        if (res.code === 200 && res.data) {
          this.treeData = res.data.tree
        } else {
          this.treeData = []
        }
      });
    },
    //搜索
    search(res) {
      this.$refs.tree.filter(res.value);
    },
    input(res) {
      this.$refs.tree.filter(res.value);
    },
    cancel(res) {
      this.$refs.tree.filter('');
    },
    //单选
    handleRadioChange(obj) {
      //console.log(obj);
      if (obj.checked) {
        this.selectValue = obj.data
      }
      // this.selectValue = this.$refs.tree.getCheckedNodes()[0]
    },
    //搜索过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //确认
    endEmployees() {
      this.loading = true
      //绑定设备
      this.$u.post(this.api.GLOBAL_device_signet_bindDevice, {
        sn: this.Bluetooth.device.sn,
        departmentId: this.selectValue.id
      }).then(res => {
        if (res.code === 200) {
          //蓝牙发送绑定设备结果
          this.BluetoothSend()
        } else {
          this.loading = false
        }
      }).catch(err => {
        //console.log(err);
        this.loading = false
      });

    },
    BluetoothSend() {
      let time = new Date().getTime()
      let body = {devId: '', activeCode: "", corpId: this.userInfo.orgId, time: time}
      //console.log(body);
      let length = this.$lizhao.scale.switch_sl(JSON.stringify(body).length, 16) // 十进制转十六进制
      let stri = '0'
      for (let i = 0; i < (7 - length.length); i++) {
        stri += '0'
      }
      //计算出body长度
      let len = stri + length //body的长度为39转成4位的16进制为00 00 00 26
      let cmd = '0007' //7转成两位的16进制为00 07
      //body转成16进制 十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      let arr = this.splitArr(hex)
      //console.log(arr);
      //多个指令串行发送，并行可能会失败
      this.writeCmd(arr, 0, '绑定设备')
    },
    //arr为hex分割的数组，i为当前数组下标
    async writeCmd(arr, i, text) {
      let res = await this.$lizhao.bluetooth.writeBLECharacteristicValue(arr[i])
      if (res === 'writeBLECharacteristicValue:ok') {
        i++
        if (i > arr.length) {
          return
        }
        this.$lizhao.sleep.sleep(50)
        this.writeCmd(arr, i, text)
      } else {
        this.aginSendFn(text)
      }

    },
    //分割指令每20位分割一下，返回数组
    splitArr(hex) {
      let arr = []
      for (let a = 0; a < Math.ceil(hex.length / 20); a++) {
        let str = hex.slice(a * 20, a * 20 + 20)
        arr.push(str)
      }
      return arr
    },
    //重发机制
    aginSendFn(text) {
      uni.showModal({
        title: this.$t('提示'),
        content: this.$t('系统繁忙'),
        cancelText: this.$t('取消'),
        confirmText: this.$t('重新发送'),
        success: ms => {
          if (ms.confirm) {
            uni.showLoading({
              title: this.$t('重新发送') + '..',
              mask: false
            });
            if (text === '绑定设备') {
              this.BluetoothSend()
            }
          }
          if (ms.cancel) {
            uni.navigateBack({
              delta: 1
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
@import './deviceBind.scss';
</style>
